package core

import (
	"fmt"
	"net/http"

	"codeberg.org/vnpower/pixivfe/v2/audit"
	"codeberg.org/vnpower/pixivfe/v2/server/session"
	"github.com/goccy/go-json"
)

func GetNewestArtworks(auditor *audit.Auditor, r *http.Request, worktype string, r18 string) ([]ArtworkBrief, error) {
	token := session.GetUserToken(r)
	URL := GetNewestArtworksURL(worktype, r18, "0")

	var body struct {
		Artworks []ArtworkBrief `json:"illusts"`
		// LastId string
	}

	resp, err := API_GET_UnwrapJson(r.Context(), auditor, URL, token, r.Header)
	if err != nil {
		return nil, err
	}
	resp, err = session.ProxyImageUrl(r, resp)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal([]byte(resp), &body)
	if err != nil {
		return nil, err
	}

	// Populate thumbnails for each artwork
	for id, artwork := range body.Artworks {
		if err := artwork.PopulateThumbnails(auditor); err != nil {
			auditor.SugaredLogger.Errorf("Failed to populate thumbnails for artwork ID %s: %v", id, err)
			return nil, fmt.Errorf("failed to populate thumbnails for artwork ID %s: %w", id, err)
		}
		body.Artworks[id] = artwork
	}

	return body.Artworks, nil
}
